<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Weixin\Controller;
use OT\DataDictionary;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class CapitalController extends WeixinController {
     protected function _initialize(){
        require_once('ThinkPHP/Library/Vendor/api_payment/llpaypayment.php');
        require_once('ThinkPHP/Library/Vendor/OCR_API.php');


        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置
        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }
        $options = array(
            'token'     => $this->token,   // 填写你设定的key
            'appid'     => $this->appid,    // 填写高级调用功能的appid
            'appsecret' => $this->appsecret // 填写高级调用功能的密钥
        );
        $this->weixin = new \Common\Extend\Wechat\Wechat($options);
        $weixin = cookie('WeixinLogin');
        if(empty($weixin)){
            $this->oauth();
        }else{
            $this->uid          = $weixin['uid'];
            $this->access_token = $weixin['access_token'];
            $this->openid       = $weixin['openid'];
        }
        $where['id'] =$this->uid;
        $count = D('ucenter_member')->where($where)->getField('mobile');
        if(empty($count)){
            $this->redirect('User/mobile');
        }
        
    }

    public function index(){
        C('WEB_SITE_TITLE','我的认证');
        $this->display();
    }


    public function test(){
        if(IS_POST){
            $t=rand(100000,999999);                                                                                                                     
            // 发送短信
            $ht=I('post.ht');
            // $one=D('Loan')->where("id=".$ht)->find();
            // $bank=D('BankCard')->where(['uid='.$one['uid'],'name'=>$one['name']])->find();
            // $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！你的合同确认验证码是'.$t.'，请勿泄露他人，请在1分钟内使用。&sendTime=&extno=';
            // $this->send_post($url);
            print_r($t);die;
        }
        C('WEB_SITE_TITLE','我的认证');
        $this->display();
    }

    public function confirm_agreement(){
        if(IS_POST){
            $t=rand(100000,999999);                                                                                                                     
            // 发送短信
            $ht=I('post.ht');
            $one=D('Loan')->where("id=".$ht)->find();
            $bank=D('BankCard')->where(['uid='.$one['uid'],'name'=>$one['name']])->find();
            $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！你的合同确认验证码是'.$t.'，请勿泄露他人，请在1分钟内使用。&sendTime=&extno=';
            $this->send_post($url);
            print_r($t);die;
        }
    }










	//系统首页
    public function loan(){
            $model = M('LoanConfig');
            $user_info = M('Member')->where("uid={$this->uid}")->field('unitname,realname,status,quota,used_money')->find();
            if(IS_POST){
                if($user_info['status']!=1){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'用户已被禁止，无法申请借款！']);
                }
                if(empty($user_info['realname'])){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'您还没有完成信息认证，无法申请借款！','url'=>U('Authentication/OCR')]);
                    
                }
                if(empty($user_info['unitname'])){
                    ob_clean();  
                    $this->AjaxReturn(['info'=>'您还没有完善个人信息，无法申请借款！','url'=>U('Member/userinfo')]);
                    
                }

                //申请中无法在提交申请
                $error = D('Loan')->tishi($this->uid);

                if($error['status']==false){   //false
                    if(!empty($error['url'])){ 
                        ob_clean();
                        $this->AjaxReturn(['info'=>$error['info'],'url'=>$error['url']]);
                      
                    }else{
                        ob_clean();
                        $this->AjaxReturn(['info'=>$error['info'],'id'=>$error['id']]);
                    }
                }


                $where['uid'] = $this->uid;
                //查看是否绑定身份证
                 if(!M('Realname')->where($where)->count()){
                     ob_clean();
                    $this->AjaxReturn(['info'=>'您还没有身份认证','url'=>U('Authentication/OCR')]);
                 }
                $where['status'] = 2;
                //查看是否绑定银行卡
                if(!M('BankCard')->where($where)->count()){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'您还没有绑定银行卡','url'=>U('Authentication/yinhang')]);
                }
                //是否认证学信网     学信认证不必须
                // if(!M('Chsi')->where($where)->count()){
                //     $this->AjaxReturn(['info'=>'您还没有学信认证','url'=>U('Authentication/xuexin')]);
                // }

                //是否认证手机号码
                if(!M('Mobileinfo')->where($where)->count()){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'您还没有手机认证','url'=>U('Authentication/mobile')]);
                }

                // 7天内有不通过审核的记录则不可以贷款
                // 不通过且cancel>0的那一次，判断是否已过7天，如需开启此功能，需在admin/capital/change中开启同样的功能
                $list=D('Loan')->where(["uid=".$this->uid,'status'=>3,'cancel'=>array('gt',0)])->find();


                $i=$list['cancel']-time()>0?1:0;
                
                $day=($list['cancel']-strtotime(date("Y-m-d")))/86400;
                if($i==1){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'距离下次可借款时间还有'.$day.'天']);
                }


                $day = I('post.day');
                $id  = I('post.id');
                $info = $model->where('id='.$id)->find();
                if(empty($info)){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'非法操作']);
                }else{
                    $price = $info['price'];
                    if($day==7){
                        $days       = $info['days_qin'];
                        $vetting1   = $info['vetting1_qin'];
                        $accrual    = $info['accrual_qin'];
                        $manag      = $info['manag_qin']; 
                    }elseif($day==14){
                        $days       = $info['days_shi'];
                        $vetting1   = $info['vetting1_shi'];
                        $accrual    = $info['accrual_shi'];
                        $manag      = $info['manag_shi'];
                    }else{
                        ob_clean();
                        $this->AjaxReturn(['info'=>'非法操作']);
                    }


                    $info22 = M('Loan')->where('uid='.$this->uid)->find(); 
                    // if(!empty($info22)){
                    //     if(!empty($user_info['quota'])){
                    //         //$vetting1 = 0; 
                    //         //$manag    = 0;
                    //         $money = $user_info['quota'] - $user_info['used_money'];
                    //         if($money<$price){
                    //             ob_clean();
                    //             $this->AjaxReturn(['info'=>'您的额度不足，无法申请借款']);
                    //         }
                    //     }
                    // }


                    $vetting1=$vetting1*$price/100;
                    $accrual=$accrual*$price/100;
                    $manag=$manag*$price/100;
                    $zhongshu       = $vetting1 + $accrual + $manag;
                    $payable      = $price - $zhongshu;
                    $real=D('Realname')->where("uid={$this->uid}")->find();

                    $data = [
                        'uid'       =>$this->uid,
                        'name'      =>$real['realname'],
                        'money'     =>$price,     //金额（贷款金额）
                        'payable'   =>$payable, //应付金额
                        'repayment' =>$price, //还款金额
                        'day'       =>$days,
                        'vetting1'  =>$vetting1,
                        'accrual'   =>$accrual,
                        'manag'     =>$manag,
                    ];
                    $Loan =  D('Loan');//print_r($data);exit;
                    $id  = $Loan->apply($data);

                    if(!empty($id)){
                        ob_clean();
                        $this->AjaxReturn(['info'=>'借款创建成功','id'=>$id]);
                    }else{
                        ob_clean();
                        $this->AjaxReturn(['info'=>'申请失败']);
                    }
                }
            }else{
                $info = $model->where('status=1')->order('price  ASC ')->select();
                //$this->assign('user_info', $user_info);
                $quota =true;
                if(!empty($user_info['quota'])){
                    $quota =false;
                }
                
                $this->assign('quota', $quota);
                $this->assign('volist', $info);
                C('WEB_SITE_TITLE','我要借款');
                $this->display();
            }
    }
    public function myloan(){
        $p = 1;
        $Loan = D('Loan');
        $list = $Loan->where('uid='.$this->uid)->page($p, 50)->select();
        $this->assign('_list', $list);
        C('WEB_SITE_TITLE','我的借款');
        $this->display();
    }

// 测试用
    //  public function myloan2(){
    //     $p = 1;
    //     $Loan = D('Loan');
    //     $list = $Loan->where('uid='.$this->uid)->order("create_time desc")->page($p, 50)->select();
    //     $this->assign('_list', $list);
    //     C('WEB_SITE_TITLE','我的借款');
    //     $this->display();
    // }
    public function loanview2(){
        $id   = I('get.id');
        $Loan = D('Loan');
        $info = $Loan->where('id='.$id)->find();
        $yh=D('BankCard')->where(array('uid'=>$info['uid'],'card_number'=>$info['bank_card']))->find();

        $openbank=$yh['openbank'];
        $this->assign('openbank',$openbank);
        $this->assign('info', $info);
        C('WEB_SITE_TITLE','借款详细');
        $this->display();
    }
    /*
     *    支付宝
     *    */
    public function alipay(){
        $type = I('get.type');
        $id   = I('get.id');
        if(!empty(I('get.day'))){
            $day=I('get.day');
        }

        if(empty($id)){
            $this->error('非法操作！');
            
        }else{

            $Loan = D('Loan');
            $vo = $Loan->where('id='.$id)->find();

            if(empty($vo)){
               $this->error('查到不到数据！');
            }elseif($vo['status']!=5&&$vo['status']!=0){
              $this->error('订单不需要还款！');
            }else{
                $bank=D('BankCard')->where(array('uid'=>$vo['uid'],'card_number'=>$vo['bank_card']))->find();
                /*延期 ----------- 开始*/ 
                if($type=='delay'){
                    $remark = '订单号'.$id;
                    $title = '订单号'.$id;
                    
                    // 逾期天数
                    $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$vo['expire_time'])))/86400;
                    if($yq_day>0){
                            
                            if($day==7){   //选择延期7天
                               $shou =  0.08;

                            }else{
                                $shou =  0.16; 
                            }
                            $money=($shou+$yq_day*0.02)*$vo['repayment'];
                    }else{
                            if($day==7){   //选择延期7天
                               $shou =  0.08;
                            }else{
                                $shou =  0.16; 
                            }
                            $money=$shou*$vo['repayment'];
                    }
                    $type = 2;                     
                    
                /*延期 ----------- 结束*/ 
                }else if($type=='promptly'){
                /*立即 ----------- 开始*/ 
                    $remark = '订单号'.$id;
                    $title  = '订单号'.$id;
                    // 逾期天数
                    $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$vo['expire_time'])))/86400;
                    // print_r($yq_day);die;
                    if($yq_day>0){
                        $money=$yq_day*0.02*$vo['repayment']+$money=$vo['repayment'];
                    }else{
                        $money=$vo['repayment'];
                    }
                    $type = 1;
                    /*立即 ----------- 结束*/ 
                }else{
                    // 缴纳审核费
                    $remark = '订单号'.$id;
                    $title  = '订单号'.$id;
                    $money=27;
                    $type = 3;

                }
                

                $data = D('Trade')->CreateTrade($vo['uid'],$id,$title,1,$type,$money,$remark);
                // print_r($data);die;
                $this->redirect('User/alipay?id='.$data['id']);
            }
        }
    }

    public function loanview(){
        $id   = I('get.id');
        $Loan = D('Loan');
        $info = $Loan->where('id='.$id)->find();
        $yh=D('BankCard')->where(array('uid'=>$info['uid'],'card_number'=>$info['bank_card']))->find();

        $openbank=$yh['openbank'];
        $this->assign('openbank',$openbank);
        $this->assign('info', $info);
        C('WEB_SITE_TITLE','借款详细');
        $this->display();
    }


    public function repayment(){
        $p = 1;
        $Loan = D('Loan');
        $where['uid']    = $this->uid;
        $where['status'] = 5;
        $list = $Loan->where($where)->page($p, 50)->select();
        $this->assign('_list', $list);
        C('WEB_SITE_TITLE','我要还款');
        $this->display();
    }


    public function agreement(){
        if(!IS_POST){
            $id   = I('get.id');
            // print_r(I('get.'));
            $info = D('Loan')->where("id=".$id)->find();

            //身份证
            $realname = M('Realname')->where(["uid="=>$info['uid'],'realname'=>$info['name']])->find();
            //银行卡
            $bankcard = M('BankCard')->where(["uid="=>$info['uid'],'card_number'=>$info['bank_card']])->find();

            $this->assign('realname', $realname);
            $this->assign('bankcard', $bankcard);
            $this->assign('info', $info);
            C('WEB_SITE_TITLE','借款服务与隐私协议');
            $this->display();
        }else{

            $id     = I('post.id');
            $type   = I('post.type');
            if(empty($id)){
                ob_clean();
                $this->AjaxReturn(['info'=>'操作成功']);
            }elseif($type!=1 && $type!=2){
                $this->error('您是否同意该合同');
            }
            $model = D('Loan');
            $where =array();
            $where['status'] = 0;
            $where['id']     = $id;

            if($type==1){       //不同意
                $list = $model->where($where)->save(['status'=>-1]);
                // $model->where("id=$id")->delete();
                $url  = U('loan');
                 if($list){
                ob_clean();
                $this->AjaxReturn(['info'=>'借款已取消','url'=>$url]);
                }else{
                    ob_clean();
                    $this->AjaxReturn(['info'=>'操作失败']);
                }
                
               
            }elseif($type==2){  //同意
                $list = $model->where($where)->save(['status'=>1]);
                $url  = U('myloan');
                if($list){
                    ob_clean();
                    $this->AjaxReturn(['info'=>'合同确认成功','url'=>$url]);
                }else{
                    ob_clean();
                    $this->AjaxReturn(['info'=>'合同确认失败']);
                }
               
            }


            



        }
    }

         //支付
    public function payment(){
        $out_trade_no       =   '5155245564656345922'; //必填，商户系统内部的订单号,32个字符内,确保在商户系统唯一
        $body               =   'dassdas'; //必填，商品描述,128 字节以下
        $total_fee          =   1; //必填，订单总金额,单位为分
        $notify_url         =   U('User/notify','',true,'weixin.jcsmkj.cn'); //必填，支付完成通知回调接口，255 字节以内
        $spbill_create_ip   =   $_SERVER['REMOTE_ADDR']; //必填，用户终端IP，IPV4字串，15字节内
        $fee_type           =   1; //必填，现金支付币种，默认1:人民币
        $bank_type          =   "WX"; //必填，银行通道类型,默认WX
        $input_charset      =   "UTF-8"; //必填，传入参数字符编码，默认UTF-8，取值有UTF-8和GBK
        $time_start         =   date("YmdHis", time() + 600); //交易起始时间,订单生成时间,格式yyyyMMddHHmmss
        $time_expire        =   ""; //交易结束时间,也是订单失效时间
        $transport_fee      =   ""; //物流费用,单位为分
        $product_fee        =   ""; //商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee
        $goods_tag          =   ""; //商品标记,优惠券时可能用到
        $attach             =   ""; //附加数据，notify接口原样返回
        $timeStamp = time();
        $options = array(
            'partnerid'     => '1268823101',                       // 主商户号
            'partnerkey'    => '74786805bf026b57965c8a94fadb258c',//商户API密钥
            'appid'         => 'wxe786085d47d6cbf4',                  // 填写高级调用功能的appid
            'appsecret'     => '147107f302f54c94f40010347934d2b1'     // 填写高级调用功能的密钥
        );
        $weixin     =  new \Common\Extend\Wechat\Wechat($options);
        $nonceStr   = $weixin->generateNonceStr();
        $package    = $weixin->createPackage($out_trade_no,$body,$total_fee,$notify_url,$spbill_create_ip,$fee_type,$bank_type,$input_charset,$time_start,$time_expire,$transport_fee,$product_fee,$goods_tag,$attach);
        $paySign    = $weixin->getPaySign($package, $timeStamp, $nonceStr);   //print_r($package);exit;
        $info = [
            'paySign'       =>$paySign,
            'timeStamp'     =>$timeStamp,
            'package'       =>$package,
            'nonceStr'      =>$nonceStr,
            'appId'         =>$options['appid'],
        ];//print_r($info);exit;

        $this->assign('info', $info);
        $this->display();
    }




    //银行卡支付
    function llpay(){
        $type = I('post.type');
        $id=I('post.id');
        $day=I('post.day');


        $is_set     =D('Loan')->where("id=$id")->find();
        $uid        =$is_set['uid']; 
        $card_number=$is_set['bank_card'];
        //银行卡号一定要对应，因为一个用户可以绑定多张银行卡
        $yinhang=D('BankCard')->where(array('uid'=>$uid,'card_number'=>$card_number))->find();
        
        $no_agree=$yinhang['no_agree'];
        $pay_num=date("YmdHis",time()).rand(100000,999999);//扣款商户订单号
        // if($is_set['pay_num']!=0){ 
        //    $pay_num= $is_set['pay_num'];
        // }else{
        //      D('Loan')->where('id='.$id)->save(['pay_num'=>$pay_num]);
        // }
        D('Loan')->where('id='.$id)->save(['pay_num'=>$pay_num]);
        

        
        $name  =$is_set['name'];
        $real       =D('realname')->where("uid=".$uid)->find();
        $id_no      =$real['identityNo'] ;//身份证号
        $no_order   =$yinhang['no_order'];
        $bind_mob   =$yinhang['mobile'];
        $res        = D('member')->where('uid='.$uid)->find();
        $reg_time   = $res['reg_time'];
        $dt_order   =date("YmdHis",time());
        


        if($type=='delay'){  //延期扣除延期费用
            if($day==7){ 
                $shou =  0.08;
            }else{
                $shou =  0.16;
            }
            // 逾期天数
            $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$is_set['expire_time'])))/86400;

            if($yq_day>0){
                $money_order=($shou+$yq_day*0.02)*$is_set['repayment'];
            }else{
                $money_order=$shou*$is_set['repayment'];
            }

        }else{
            
            // 逾期天数
            $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$is_set['expire_time'])))/86400;
            if($yq_day>0){
                $money_order=$yq_day*0.02*$is_set['repayment']+$is_set['repayment'];
            }else{
                $money_order=$is_set['repayment'];
            }
        }
       
        // echo $yq_day;die;
        // ob_clean();
        // $this->AjaxReturn($yq_day);
        
        //由该方法组装所有参数包括签名，商户号等信息
        $r=Installment($uid,$no_agree,$pay_num,$money_order,$name,$id_no,$no_order,$bind_mob,$reg_time,$dt_order);
        ob_clean();

        $this->AjaxReturn($r);
    }


    // 连连主动还款接口支付成功访问的地址
    public function llpay_notify(){

        if(IS_POST){

            $data=I('post.res_data');
            

            $data= str_replace(PHP_EOL, '', $data);
            $data=json_decode($data,true);

            $no_order=$data['no_order'];//商户系统订单号（唯一）
            $money=$data['money_order']; //付款金额
            $one=D('Loan')->where("pay_num=".$no_order)->find();
            $yinhang=D('BankCard')->where(array('uid'=>$one['uid'],'card_number'=>$one['bank_card']))->find();


            $m1=$one['repayment']; //未到期，全额还款
            $m2=0.08*$one['repayment']; //未到期，延期7天
            // $m2=0.02;
            $m3=0.16*$one['repayment']; //未到期，延期14天

            $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$one['expire_time'])))/86400;


            // echo $yq_day.'<br>';


            if($yq_day>0){

                $m4=$one['repayment']+0.02*$one['repayment']*$yq_day; //逾期后还款，不延期
                $m5=0.08*$one['repayment']+0.02*$one['repayment']*$yq_day; //逾期后延款7天
                $m6=0.16*$one['repayment']+0.02*$one['repayment']*$yq_day; //逾期后延款14天
            }

            
            if($money==$m1||$money==$m4){
                //提前主动还款
                $oid_paybill=$data['oid_paybill'];//支付平台订单号
                // 将所需数据存入数据库
                //将已用额度恢复为0，那么额可用额度恢复到最初
                $mem=D('Member')->where('uid='.$one['uid'])->save(['used_money'=>0.00]);
                $result=D('Loan')->where("pay_num=".$no_order)->save(['oid_returnbill'=>$oid_paybill,'status'=>6,'huankuan_time'=>time(),'repay_method'=>1,'pay_num'=>$no_order]);
                // //微信提醒
                $datas = [
                    'title'=>'还款成功',
                    'money'=>$one['money'],
                    'type'=>'还款',
                    'status'=>'成功还款',
                    'mydate'=>date('Y-m-d H:i',$one['expire_time']),
                    'date'=>date('Y-m-d H:i'),
                    'remark'=>'您已还款成功，感谢您的使用！',
                ];
                $url = U('Capital/loanview?id='.$one['id'],'',true,'weixin.jcsmkj.cn');
                D('Notice')->weixin(5,$one['uid'],$datas,$url);
                
                // 发送短信
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$yinhang['mobile'].'&content=【西西钱包】'.$yinhang['name'].'您好！您已通过银行卡主动还款，已为您恢复额度，可继续使用，客服热线0771-5717965&sendTime=&extno=';
                $this->send_post($url);
            }else if($money==$m2){

                $expire_time=$one['expire_time']+7*86400;
                D('Loan')->where("pay_num=".$no_order)->save(['expire_time'=>$expire_time,'pay_num'=>0]);

                $data = [
                        'day'=>14,
                        'date'=>date("Y年m月d日",$expire_time),
                        'money'=>$money,
                        'repayment'=>$one['repayment'],
                        'remark'=>'延期成功',
                ];
                $url = U('Capital/loanview?id='.$one['id'],'',true,'weixin.jcsmkj.cn');
                D('Notice')->weixin(9,$one['uid'],$data,$url);

                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$yinhang['mobile'].'&content=【西西钱包】'.$yinhang['name'].'您好！延期成功，您已支付'.$money.'元费用延期至'.date("Y年m月d日",$expire_time).'，小西祝您生活愉快！&sendTime=&extno=';
                $this->send_post($url);

            }else if($money==$m3){
                $expire_time=$one['expire_time']+14*86400;
                D('Loan')->where("pay_num=".$no_order)->save(['expire_time'=>$expire_time,'pay_num'=>0]);
               $data = [
                        'day'=>7,
                        'date'=>date("Y年m月d日",$expire_time),
                        'money'=>$money,
                        'repayment'=>$one['repayment'],
                        'remark'=>'延期成功',
                ];
                $url = U('Capital/loanview?id='.$one['id'],'',true,'weixin.jcsmkj.cn');
                D('Notice')->weixin(9,$one['uid'],$data,$url);
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$yinhang['mobile'].'&content=【西西钱包】'.$yinhang['name'].'您好！延期成功，您已支付'.$money.'元费用延期至'.date("Y年m月d日",$expire_time).'，小西祝您生活愉快！&sendTime=&extno=';
                $this->send_post($url);
            }else if(isset($m5)&&$money==$m5){
                $expire_time=time()+7*86400;
                D('Loan')->where("pay_num=".$no_order)->save(['expire_time'=>$expire_time,'pay_num'=>0]);
                $data = [
                        'day'=>7,
                        'date'=>date("Y年m月d日",$expire_time),
                        'money'=>$money,
                        'repayment'=>$one['repayment'],
                        'remark'=>'延期成功',
                ];
                $url = U('Capital/loanview?id='.$one['id'],'',true,'weixin.jcsmkj.cn');
                D('Notice')->weixin(9,$one['uid'],$data,$url);
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$yinhang['mobile'].'&content=【西西钱包】'.$yinhang['name'].'您好！延期成功，您已支付'.$money.'元费用延期至'.date("Y年m月d日",$expire_time).'，小西祝您生活愉快！&sendTime=&extno=';
                $this->send_post($url);
            }else if(isset($m6)&&$money==$m6){
                $expire_time=time()+14*86400;
                D('Loan')->where("pay_num=".$no_order)->save(['expire_time'=>$expire_time,'pay_num'=>0]);
                $data = [
                        'day'=>14,
                        'date'=>date("Y年m月d日",$expire_time),
                        'money'=>$money,
                        'repayment'=>$one['repayment'],
                        'remark'=>'延期成功',
                ];
                $url = U('Capital/loanview?id='.$one['id'],'',true,'weixin.jcsmkj.cn');
                D('Notice')->weixin(9,$one['uid'],$data,$url);
                $url='http://sh2.ipyy.com/sms.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$yinhang['mobile'].'&content=【西西钱包】'.$yinhang['name'].'您好！延期成功，您已支付'.$money.'元费用延期至'.date("Y年m月d日",$expire_time).'，小西祝您生活愉快！&sendTime=&extno=';
                $this->send_post($url);
            }
           
        }
    }


     //授权申请API  $card_number,$money_order,$acct_name,$oid_paybill
     function agreenoauthapply(){
        $type=I('post.type');
        $id=I('post.id');
        $is_set=D('Loan')->where("id=$id")->find();

      
        $uid=$is_set['uid']; 
        $card_number=$is_set['bank_card'];
        //银行卡号一定要对应，因为一个用户可以绑定多张银行卡
        $yinhang=D('BankCard')->where(array('uid'=>$uid,'card_number'=>$card_number))->find();
    
        $no_agree=$yinhang['no_agree'];
        
        $repayment_no =date("YmdHis",time()).rand(100000,999999);
        
        if($is_set['repayment_no']!=0){ //如果该用户的该还款计划编号已存在,则不需要再次更换还款计划编号
           $repayment_no= $is_set['repayment_no'];
        }else{
            D('Loan')->where('id='.$id)->save(['repayment_no'=>$repayment_no]);
        }
        $date=time();//计划还款日期
        $yq_day=(strtotime(date("Y-m-d"))-strtotime(date("Y-m-d",$is_set['expire_time'])))/86400; //逾期天数计算

        if($yq_day>0){
            $money=$is_set['repayment']+0.02*$is_set['repayment']*$yq_day; //逾期后还款，不延期
        }else{
            $money=$is_set['repayment'];   //未逾期
        }
        $r=Agreenoauthapply($uid,$no_agree,$date,$money,$repayment_no); 
        $r=json_decode($r,true);
         // print_r($r);die;
        
        if($r['ret_code']=='0000'){
            $re=$this->bankcardrepayment($id,$date,$money);
            $re=json_decode($re,true);
            if($re['ret_code']=='0000'){



                
                ob_clean();
                $this->AjaxReturn(['info'=>'提交成功！']);
            }else{
                ob_clean();
                $this->AjaxReturn(['info'=>$re['ret_msg']]);
            }
            
        }else{
            ob_clean();
            $this->AjaxReturn(['info'=>$r['ret_code']]);
        }
    }
// 扣款还款申请
    function bankcardrepayment($id,$date,$money){
        // $id         =201709156838361504;
        $is_set     =D('Loan')->where("id=$id")->find();
        $uid        =$is_set['uid']; 
        $card_number=$is_set['bank_card'];
        //银行卡号一定要对应，因为一个用户可以绑定多张银行卡
        $yinhang=D('BankCard')->where(array('uid'=>$uid,'card_number'=>$card_number))->find();
        
        $no_agree=$yinhang['no_agree'];
        $pay_num=date("YmdHis",time()).rand(100000,999999);
        if($is_set['pay_num']!=0){ //如果该用户的该商户系统订单号已存在,则不需要再次更换商户系统订单号
           $pay_num= $is_set['pay_num'];
        }else{
            D('Loan')->where('id='.$id)->save(['pay_num'=>$pay_num]);
        }
        $repayment      =$money;
        $expire_time    =$date;
        $repayment_no   =$is_set['repayment_no'];

        
        $name       =$is_set['name'];
        $real       =D('realname')->where("uid=".$uid)->find();
        $id_no      =$real['identityNo'] ;//身份证号
        $no_order   =$yinhang['no_order'];
        $bind_mob   =$yinhang['mobile'];
        $res        = D('member')->where('uid='.$uid)->find();
        $reg_time   = $res['reg_time'];
        $dt_order   =date("YmdHis",time());  //存下订单时间 查询时需要使用
        D('Loan')->where('id='.$id)->save(['dt_order'=>$dt_order]);
        
                           //$uid,$no_agree,$pay_num,$repayment,$expire_time,$repayment_no,$name,$id_no,$no_order,$bind_mob,$reg_time 
        $r=Bankcardrepayment($uid,$no_agree,$pay_num,$repayment,$expire_time,$repayment_no,$name,$id_no,$no_order,$bind_mob,$reg_time,$dt_order);
        return $r;

    }



    // /**
    //  * 发送post请求
    //  * @param string $url 请求地址
    //  * @param array $post_data post键值对数据
    //  * @return string
    //  */
    function send_post($url) {
        $post_data = array(
          'username' => 'jkwl362',
          'password' => 'ndp987'
        );
     
      $postdata = http_build_query($post_data);
      $options = array(
        'http' => array(
          'method' => 'POST',
          'header' => 'Content-type:application/x-www-form-urlencoded',
          'content' => $postdata,
          'timeout' => 60 // 超时时间（单位:s）
        )
      );
      $context = stream_context_create($options);
      $result = file_get_contents($url, false, $context);
    }  



    public function payout(){

        $id=I('post.id');


        print_r('暂时不可使用此功能');die;


        $time=D('Timeout')->where(['uid'=>$this->uid])->find();
        if($time['time']<time()){
            // 订单失效，将订单状态改为取消状态
            D('Loan')->where('id='.$id)->save(['status'=>-1]);
            print_r(0);die;
        }
        // else{
        //     print_r('还在订单有效时间');

        // }
        // die;


        
        $card=D('BankCard')->where('uid='.$this->uid)->find();
        $card_no=$card['card_number'];

        //商户付款流水号,唯一标识，不可重复
        $no_order =date("YmdHis").rand(100000,999999);
        $is_set=D('Loan')->where('id='.$id)->find();
        if($is_order_num['order_num']!=0){ //如果该用户的该流水号已存在,则不需要再次更换流水号
           $no_order= $is_set['order_num'];
        }else{
            D('Loan')->where("id=$id")->save(['order_num'=>$no_order]);
        }
        // echo  $no_order;die;
        
        
        //商户时间 ，商户提交订单时间
        $dt_order = date("YmdHis",time());
        //金额
        $money_order =$is_set['payable'];
        //收款人姓名
        $acct_name = $is_set['name'];
        //银行账号
        $card_no=$card['card_number'];
        //订单描述
        $info_order = '实时代付';
        //对私标记
        $flag_card = '0';
        //服务器异步通知地址(打款成功之后通知的地址)
        $notify_url = 'http://weixin.jcsmkj.cn/index.php?m=admin&c=notify&a=notify';

        $r=Payment($no_order,$dt_order,$money_order,$acct_name,$card_no,$info_order,$flag_card,$notify_url);


        ob_clean();
        $r=json_decode($r,true);



        // print_r($r);die;

        if(!empty($r['oid_paybill'])){
            $oid_paybill=$r['oid_paybill']; //支付单号 
            D('Loan')->where("id=$id")->save(['oid_paybill'=>$oid_paybill]);
        }
        if(!empty($r['confirm_code'])){
            // print_r($r['confirm_code']);
            $code=$r['confirm_code'];   //校验码
            D('Loan')->where("id=$id")->save(['code'=>$code]);

        }
        
        if($r['ret_code']=='0000'){ //申请成功
             
             $data=array(
                'uid'=>$v_a['uid'],
                'time'=>time(),
                'text'=>'打款操作',
                'maker'=>$this->uid,//系统操作
                );
            D('LoanDefault')->add($data);
            print_r(1);die;
            // print_r('打款申请成功，请等待资金到账');die;

        }else{
            print_r($r['ret_code'].'///'.$r['ret_msg']);die;
            // print_r('打款申请失败，原因是：'.$r['ret_code'].$r['ret_msg'].',可截图此原因发至客服解决');die;
        }

    }  




}